package com.atguigu.gulimall.thirdpart.controller.wechat.controller;

import com.atguigu.common.utils.R;
import com.atguigu.gulimall.thirdpart.controller.wechat.entity.UserAccessToken;
import com.atguigu.gulimall.thirdpart.controller.wechat.entity.WeChatUserInfo;
import com.atguigu.gulimall.thirdpart.controller.wechat.service.AuthorizeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author zhangxueyou
 * @date 2020/10/2-17:34
 */
@Slf4j
@Controller
@RequestMapping("/wechat")
public class WxWebAuthController {
    @Value("${wx.configs.appid}")
    private String appId;
    @Value("${wx.configs.secret}")
    private String secret;
    @Value("${wx.configs.token}")
    private String token;

    @Autowired
    private AuthorizeService authorizeService;

    /**
     * 1).引导用户点击授权连接
     * 2).点击授权后携带code访问本方服务器
     * 3).
     * 网页授权获取公众号用户信息
     */
    @ResponseBody
    @RequestMapping("/web/auth")
    public R webAuth(String code) {
        log.info("=====微信服务器携带code访问===>[code={}]", code);
        //带着code请求微信，去获取access_token
        UserAccessToken userAcsTokenByCode = authorizeService.getUserAcsTokenByCode(appId, secret, code);
        log.info("=====微信服务器携带token访问===>[token={}]", userAcsTokenByCode);
        //取出token，请求微信返回用户信息
        WeChatUserInfo info = authorizeService.getWeChatUnSubscribeUserInfo(userAcsTokenByCode.getAccess_token(), userAcsTokenByCode.getOpenid());
        log.info("=====微信服务器返回token访问===>[info={}]", info);
        System.out.println(info.toString());
        return R.ok("授权成功");
    }

}
